package ale.android.mapping;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.xml.sax.SAXException;

import android.util.Log;


public class RoadProvider {

	public static Road getRoute(String response) {
		Road road = new Road();
		
		try {						
			JSONObject jsonresponse = (JSONObject) new JSONTokener(response).nextValue();
			JSONArray steps = jsonresponse.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
			
			ArrayList<Double> lats = new ArrayList<Double>();
			ArrayList<Double> longs = new ArrayList<Double>();
			for(int i=0; i<steps.length(); i++){
				lats.add(steps.getJSONObject(i).getJSONObject("start_location").getDouble("lat"));
				longs.add(steps.getJSONObject(i).getJSONObject("start_location").getDouble("lng"));
			}
			
			double[][] route = new double[lats.size()][2];
			for(int i=0; i<lats.size(); i++){
				route[i][1] = lats.get(i);
				route[i][0] = longs.get(i);
			}
			
			road.mRoute = route;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return road;
	}

	public static String getUrl(double fromLat, double fromLon, double toLat,
			double toLon) {// connect to map web service
		StringBuffer urlString = new StringBuffer();
		urlString.append("http://maps.googleapis.com/maps/api/directions/json");
		urlString.append("?origin=");// from
		urlString.append(Double.toString(fromLat));
		urlString.append(",");
		urlString.append(Double.toString(fromLon));
		urlString.append("&destination=");// to
		urlString.append(Double.toString(toLat));
		urlString.append(",");
		urlString.append(Double.toString(toLon));
		urlString.append("&sensor=true&mode=walking");
		return urlString.toString();
	}
}